package cn.stu.flowable.controller;


import cn.stu.common.utils.R;
import cn.stu.flowable.domain.vo.FlowTaskVo;
import cn.stu.flowable.service.IFlowInstanceService;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * 流实例控制器
 * 工作流流程实例管理
 *
 * @author Tony
 * @date 2021-04-03
 * @menu 工作流流程实例管理
 */
@Slf4j
@RestController
@RequestMapping("/flowable/instance")
@AllArgsConstructor
public class FlowInstanceController {

    /**
     * 流实例服务
     */
    private IFlowInstanceService flowInstanceService;

    /**
     * 根据流程定义id启动流程实例
     *
     * @param procDefId 进程定义ID
     * @param variables 变数
     * @return {@link R}
     */
    @PostMapping("/startBy/{procDefId}")
    public R startById(@ApiParam(value = "流程定义id") @PathVariable(value = "procDefId") String procDefId,
                       @ApiParam(value = "变量集合,json对象") @RequestBody Map<String, Object> variables) {
        return flowInstanceService.startProcessInstanceById(procDefId, variables);

    }


    /**
     * 激活或挂起流程实例
     *
     * @param state      状态
     * @param instanceId 实例ID
     * @return {@link R}
     */
    @PostMapping(value = "/updateState")
    public R updateState(@ApiParam(value = "1:激活,2:挂起", required = true) @RequestParam Integer state,
                         @ApiParam(value = "流程实例ID", required = true) @RequestParam String instanceId) {
        flowInstanceService.updateState(state, instanceId);
        return R.ok();
    }

    /**
     * 结束流程实例
     *
     * @param flowTaskVo 流任务VO
     * @return {@link R}
     */
    @PostMapping(value = "/stopProcessInstance")
    public R stopProcessInstance(@RequestBody FlowTaskVo flowTaskVo) {
        flowInstanceService.stopProcessInstance(flowTaskVo);
        return R.ok();
    }

    /**
     * 删除流程实例
     *
     * @param instanceIds  实例ID
     * @param deleteReason 删除原因
     * @return {@link R}
     */
    @DeleteMapping(value = "/{instanceIds}")
    public R delete(@ApiParam(value = "流程实例ID", required = true) @PathVariable String[] instanceIds,
                    @ApiParam(value = "删除原因") @RequestParam(required = false) String deleteReason) {
        for (String instanceId : instanceIds) {
            flowInstanceService.delete(instanceId, deleteReason);
        }
        return R.ok();
    }
}